import axios from 'axios'
import qs from 'qs'

const SERVER = 'https://application.huhuiyu.top'

const tokenkey = SERVER + '_tokenkey'

const tokeninfo = {
  load: () => {
    let token = localStorage.getItem(tokenkey)
    return token ? token : ''
  },
  save: (data) => {
    // 如果应答信息中存在token就保存到本地存储
    if (data && data.token) {
      localStorage.setItem(tokenkey, data.token)
    }
  },
  clear: () => {
    localStorage.removeItem(tokenkey)
  },
}

const application = {
  // 用户头像
  uploadUserLogo: (file, cb) => {
    // 上传文件必须使用FormData
    const formdata = new FormData()
    formdata.append('file', file)
    const url = SERVER + '/user/logo'
    const promise = axios({
      url: url,
      method: 'POST',
      data: formdata,
      headers: {
        // 通过头信息传递token认证信息
        Authorization: tokeninfo.load(),
        // 上传文件的指定类型
        'Content-Type': 'multipart/form-data',
      },
    })
    promise
      .then((resp) => {
        console.log('应答结果:', resp)
        // 保存token认证信息
        tokeninfo.save(resp.data)
        cb(resp.data)
      })
      .catch((err) => {
        console.log('请求出错:', err)
        cb({ success: false, message: '出bug了,赶紧叫老师来改代码' })
      })
  },

  userlogo: (id) => {
    return `${SERVER}/user/logo/${id}?ts=${new Date().getTime()}`
  },

  test: () => {
    console.log('测试信息:', axios, qs)
  },

  // 发起ajax请求的方法，请求的要素：请求的地址，请求的参数，请求的方式，结果处理
  send: (url, param, method, cb) => {
    // 将请求的方式替换成大写
    method = method ? method.toUpperCase() : 'GET'
    // 完整的url
    url = SERVER + url
    // get请求需要转化参数为查询字符串并拼接到url
    if (method == 'GET') {
      url += `?` + qs.stringify(param)
      param = ''
    }
    // 通过axios发起请求
    let promise = axios({
      url: url,
      method: method,
      data: param,
      headers: {
        // 通过头信息传递token认证信息
        Authorization: tokeninfo.load(),
      },
    })

    promise
      .then((resp) => {
        console.log('应答结果:', resp)
        // 保存token认证信息
        tokeninfo.save(resp.data)
        cb(resp.data)
      })
      .catch((err) => {
        console.log('请求出错:', err)
        cb({ success: false, message: '出bug了,赶紧叫老师来改代码' })
      })
  },

  // get请求
  get: (url, param, cb) => {
    application.send(url, param, 'GET', cb)
  },

  // post请求
  post: (url, param, cb) => {
    application.send(url, param, 'POST', cb)
  },

  // delete请求
  delete: (url, param, cb) => {
    application.send(url, param, 'DELETE', cb)
  },

  // put请求
  put: (url, param, cb) => {
    application.send(url, param, 'PUT', cb)
  },

  // patch请求
  patch: (url, param, cb) => {
    application.send(url, param, 'PATCH', cb)
  },
}

export { application as default, application }
